/*
 * Copyright (C) 2012 DataSymphony (http://datasymphony.com.au)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package au.com.ds.restty;

import java.util.HashMap;

import au.com.ds.restty.fmt.Formatter;
import au.com.ds.restty.fmt.FormatterFactory;
import au.com.ds.restty.fmt.FormatterType;
import au.com.ds.restty.js.JsAnyObject;
import au.com.ds.restty.js.JsObject;
import au.com.ds.restty.js.JsObjectFactory;

public class Out {
	public enum Level {
		min, normal, debug		
	}
	
	private static Level cLevel = Level.min;
	
	public static Level getLevel() {
		return cLevel;
	}
	
	public static void min(String message){
		print(Level.min, message);
	}

	public static void normal(String message){
		print(Level.normal, message);
	}

	public static void debug(String message){
		print(Level.debug, message);
	}

	protected static void setLevel(Level level) {
		cLevel = level;
	}
	
	@SuppressWarnings("serial")
	protected static void finalError(final String message) {
		String result;
		
		if (cLevel == Level.min) {
			JsObject resultObject = JsObjectFactory.getJsObject(new HashMap<JsAnyObject, JsAnyObject>(){{
				put(JsObjectFactory.getJsString("error"), 
						JsObjectFactory.getJsString("ERROR during command execution (See restty.log for the details)."));
				put(JsObjectFactory.getJsString("details"), JsObjectFactory.getJsString(message));
			}});
			
			Formatter fmt = FormatterFactory.getFormatter(FormatterType.JSON);
			result = fmt.format(resultObject, null);
		} else {
			result = "ERROR during command execution (See restty.log for the details):\n\t" + message;
		}
		
		System.out.println(result);
	}
	
	private static void print(Level level, String message){
		if (level.ordinal() <= cLevel.ordinal()) {
			System.out.println(message);
		}
	}
}
